local function trim_empty_lines(lines)
  -- Join lines into a single string and split them by line breaks
  local joined_lines = table.concat(lines, "\n")
  local split_lines = vim.split(joined_lines, "\n", { trimempty = true })

  return split_lines
end

vim.lsp.handlers["textDocument/hover"] = function(_, result, ctx, config)
  config = config or {}
  config.focus_id = ctx.method
  if not (result and result.contents) then
    return
  end
  local markdown_lines = vim.lsp.util.convert_input_to_markdown_lines(result.contents)
  markdown_lines = trim_empty_lines(markdown_lines)
  if vim.tbl_isempty(markdown_lines) then
    return
  end
  return vim.lsp.util.open_floating_preview(markdown_lines, "markdown", config)
end

local function remapKeys()
  local keys = require("lazyvim.plugins.lsp.keymaps").get()
  keys[#keys + 1] = { "K", false, mode = "n" }
  keys[#keys + 1] = { "<c-k>", false, mode = "i" }
  keys[#keys + 1] = { "gh", vim.lsp.buf.hover, desc = "Hover" }
  -- disable old mappings
  keys[#keys + 1] = { "<leader>ca", false }
  keys[#keys + 1] = { "<leader>cc", false }
  keys[#keys + 1] = { "<leader>cC", false }
  keys[#keys + 1] = { "<leader>cR", false }
  keys[#keys + 1] = { "<leader>cr", false }
  keys[#keys + 1] = { "<leader>cA", false }
  -- enable new mappings
  keys[#keys + 1] =
    { "<leader>la", vim.lsp.buf.code_action, desc = "Code Action", mode = { "n", "v" }, has = "codeAction" }
  keys[#keys + 1] = { "<c-.>", vim.lsp.buf.code_action, desc = "Code Action", mode = { "n", "v" }, has = "codeAction" }
  keys[#keys + 1] = { "<leader>lc", vim.lsp.codelens.run, desc = "Run Codelens", mode = { "n", "v" }, has = "codeLens" }
  keys[#keys + 1] =
    { "<leader>lC", vim.lsp.codelens.refresh, desc = "Refresh & Display Codelens", mode = { "n" }, has = "codeLens" }
  -- keys[#keys + 1] = {
  --   "<leader>lR",
  --   Snacks.rename,
  --   desc = "Rename File",
  --   mode = { "n" },
  --   has = { "workspace/didRenameFiles", "workspace/willRenameFiles" },
  -- }
  keys[#keys + 1] = { "<leader>lr", vim.lsp.buf.rename, desc = "Rename", has = "rename" }
  keys[#keys + 1] = { "<leader>lA", LazyVim.lsp.action.source, desc = "Source Action", has = "codeAction" }
  -- custom mappings
  keys[#keys + 1] = { "<F2>", vim.lsp.buf.rename, desc = "Rename", has = "rename" }
end

local function setupDeno()
  local util = require 'lspconfig.util'
  vim.lsp.config("denols", {
    root_dir = util.root_pattern("deno.json", "deno.jsonc"),
  })
end

local function setupCapCds()
  -- require("lspconfig").cds_lsp.setup({})
  vim.lsp.enable("cds_lsp")
end

return {
  "neovim/nvim-lspconfig",

  init = function()
    remapKeys()
    setupDeno()
    setupCapCds()
  end,

  opts = {
    servers = {
      ts_ls = {
        enabled = false,
      },
      vtsls = {
        enabled = false,
      },
    },
    inlay_hints = { enabled = false },
  },
}
